package com.mainaer.wjokhttp.ui;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.widget.AbsListView;
import android.widget.ListView;

import com.mainaer.wjokhttp.R;
import com.mainaer.wjokhttp.comment.BaseAppCompatActivity;
import com.mainaer.wjokhttp.model.MovieListResponse;
import com.mainaer.wjokhttp.comment.OkUtils;
import com.mainaer.wjokhttp.controller.MovieListController;
import com.mainaer.wjokhttp.ui.adapter.MovieListAdapter;
import com.mainaer.wjoklib.okhttp.exception.OkHttpError;
import com.mainaer.wjoklib.okhttp.utils.WLog;
import com.mainaer.wjoklib.okhttp.utils.WToast;

import java.util.ArrayList;

/**
 * 主页界面
 */
public class MainActivity extends BaseAppCompatActivity implements MovieListController.MovieListListener {

    private ListView mListview;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private SearchView mSearchView;

    private MovieListController mMovieListController;
    private MovieListAdapter mMovieListAdapter;

    // 当前加载的页数
    private int mCurrentPage = 1;
    // 所有数据是否加载完成
    private boolean mAllLoadFinish;
    // 当前加载任务是否完成
    private boolean mTaskFinish;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        // init view

        mSwipeRefreshLayout = $(R.id.swipe_layout);
        mListview = $(R.id.listview);
        mSearchView = $(R.id.search_view);
        mSearchView.setSubmitButtonEnabled(true);
        // init controller
        mMovieListController = new MovieListController(this);

        // init adapter
        mMovieListAdapter = new MovieListAdapter(this);
        mListview.setAdapter(mMovieListAdapter);

        // listview 滚动监听
        mListview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        // 滚动到最后一行的时候，加载更多数据
                        String query = mSearchView.getQuery().toString();
                        // 所有数据加载完成或当前任务没有完成
                        if (mAllLoadFinish || !mTaskFinish) {
                            return;
                        }
                        loadData(false, query);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        // 下拉刷新
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                String query = mSearchView.getQuery().toString();
                loadData(true, query);
            }
        });

        // SearchView 监听器
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                loadData(true, query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {
                WLog.d(query);
                // 搜索添加变化时，重置加载状态
                mAllLoadFinish = false;
                if (TextUtils.isEmpty(query)) {
                    loadData(true, null);
                }
                return false;
            }
        });
    }

    // 加载列表
    @Override
    public void initData() {
        // 初次加载显示正在加载圆圈
        mSwipeRefreshLayout.setRefreshing(true);
        loadData(true, null);
    }

    /**
     * 加载数据
     *
     * @param firstLoad 是否第一次加载
     * @param query     查询的文字
     */
    private void loadData(boolean firstLoad, String query) {
        mTaskFinish = false;
        if (firstLoad) {
            mCurrentPage = 1;
        }
        query = TextUtils.isEmpty(query) ? "harry" : query;

        // 发送网络请求
        mMovieListController.loadMovieList(query, mCurrentPage);
    }

    @Override
    public void onLoadMovieListSuccess(MovieListResponse loadResponse) {
        if (mCurrentPage == 1) {
            mMovieListAdapter.setDataList((ArrayList<MovieListResponse.SearchBean>) loadResponse.Search);
        } else {
            mMovieListAdapter.getDataList().addAll(loadResponse.Search);
        }
        mMovieListAdapter.notifyDataSetChanged();

        // 更新当前请求加载状态
        mTaskFinish = true;
        // 隐藏加载框
        mSwipeRefreshLayout.setRefreshing(false);

        // 数据加载完
        if (mMovieListAdapter.getDataList().size() == Integer.parseInt(loadResponse.totalResults)) {
            mAllLoadFinish = true;
            WToast.showToast(this, R.string.text_load_finish);
            return;
        }

        mCurrentPage++;
    }

    @Override
    public void onLoadMovieListFail(OkHttpError okHttpError) {
        mTaskFinish = true;
        mSwipeRefreshLayout.setRefreshing(false);
        // 防止加载失败，多次计算页数
        if (mCurrentPage > 1) {
            mCurrentPage--;
        }
        // 显示异常信息
        if (TextUtils.equals(okHttpError.getMessage(), "Movie not found!")) {
            mMovieListAdapter.clearData();
            mMovieListAdapter.notifyDataSetChanged();
        }

        OkUtils.toastError(this, okHttpError);
    }
}
